package com.shylock.as.api.filter;

import com.alibaba.fastjson.JSON;
import com.shylock.as.entity.User;
import com.shylock.as.util.JedisUtil;
import com.shylock.common.config.RedisKeyConfig;
import com.shylock.common.config.SystemConfig;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

/**
 * @description：
 * @author: Shylock
 * @time：2021/10/19 21:21
 */
@WebFilter
public class AuthFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        //获取令牌
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        String token = request.getHeader(SystemConfig.HEADER_TOKEN);
        //校验令牌是否存在
        String key = RedisKeyConfig.LOGIN_TOKEN+token;
        if(JedisUtil.checkKey(key)){
            //查询到令牌，续期时间+30分钟
            String phone = JSON.parseObject(JedisUtil.getStr(key), User.class).getPhone();
            JedisUtil.expire(RedisKeyConfig.LOGIN_PHONE+phone,RedisKeyConfig.LOGIN_TOKEN_TIME);
            JedisUtil.expire(key,RedisKeyConfig.LOGIN_TOKEN_TIME);
        }
        filterChain.doFilter(request,servletResponse);
    }

    @Override
    public void destroy() {

    }
}
